import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
from sklearn.datasets import make_regression
from sklearn.datasets import load_iris
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
from sklearn.cluster import KMeans
from sklearn.datasets import make_blobs
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.naive_bayes import MultinomialNB
# 线性回归
def linear_regression_example():
    # 生成模拟数据
    X, y = make_regression(n_samples=100, n_features=1, noise=20, random_state=42)
    # 初始化线性回归模型
    model = LinearRegression()
    # 训练模型
    model.fit(X, y)
    # 预测
    y_pred = model.predict(X)
    # 绘制结果
    plt.scatter(X, y)
    plt.plot(X, y_pred, color='red')
    plt.xlabel('特征')
    plt.ylabel('房价')
    plt.show()
# 决策树分类
def decision_tree_example():
    # 加载鸢尾花数据集
    iris = load_iris()
    X = iris.data
    y = iris.target
    # 划分训练集和测试集
    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
    # 初始化决策树模型
    model = DecisionTreeClassifier()
    # 训练模型
    model.fit(X_train, y_train)
    # 预测
    y_pred = model.predict(X_test)
    # 评估准确率
    accuracy = accuracy_score(y_test, y_pred)
    print(f"决策树模型准确率: {accuracy}")
# K - 均值聚类
def kmeans_example():
    # 生成模拟数据
    X, _ = make_blobs(n_samples=300, centers=4, cluster_std=0.60, random_state=0)
    # 初始化K - 均值模型，设置聚类中心数为4
    kmeans = KMeans(n_clusters=4, random_state=0)
    # 拟合数据
    kmeans.fit(X)
    # 预测每个数据点所属的簇
    labels = kmeans.labels_
    # 绘制聚类结果
    plt.scatter(X[:, 0], X[:, 1], c=labels)
    plt.xlabel('特征1')
    plt.ylabel('特征2')
    plt.show()
# 朴素贝叶斯分类
def naive_bayes_example():
    # 模拟邮件文本和标签（0 表示正常邮件，1 表示垃圾邮件）
    emails = ["buy now", "hello friend", "get rich quick", "how are you"]
    labels = [1, 0, 1, 0]
    # 将文本转换为特征向量
    vectorizer = CountVectorizer()
    X = vectorizer.fit_transform(emails)
    # 初始化朴素贝叶斯模型
    model = MultinomialNB()
    # 训练模型
    model.fit(X, labels)
    # 预测新文本
    new_emails = ["new product", "good day"]
    new_X = vectorizer.transform(new_emails)
    y_pred = model.predict(new_X)
    print("朴素贝叶斯预测结果:", y_pred)
if __name__ == "__main__":
    linear_regression_example()
    decision_tree_example()
    kmeans_example()
    naive_bayes_example()